package com.renwei.yunlong.activity.news;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.ChatAddBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.event.ChatCloseEvent;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.message.InformationNotificationMessage;

/**
 * Project :  yunaandroid.
 * Package name: com.renwei.yunlong.activity
 * Created by :  Benjamin.
 * Created time: 2017/12/12 16:30
 * Changed by :  Benjamin.
 * Changed time: 2017/12/12 16:30
 * Class description:
 */

public class TranspaintActivity extends BaseActivity implements HttpTaskListener {
    public static String groupId = "";

    public static String getGroupId() {
        return groupId;
    }

    public static void setGroupId(String groupId) {
        TranspaintActivity.groupId = groupId;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transpaint);
        Window window = getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        wl.alpha = 0.0f;//这句就是设置窗口里控件的透明度的．０.０全透明．１.０不透明．
        window.setAttributes(wl);
        onCommitAndAdd();
    }

    public void onCommitAndAdd() {
        //  2017/12/8 11:16  底部提交按钮就是创建 群组会话
        if (UtilList.getCount(AppHelper.getCheckContactList()) == 0) {
            showCenterInfoMsg("请选择群组人员");
            finish();
            return;
        }
        if (TextUtils.isEmpty(getGroupId())) { //
            creatGroup();
        } else { // 新增
            insteadGroup();
        }
    }


    // : 2017/12/8 起调环信创建群组
    private void creatGroup() {
        int selectCount = UtilList.getCount(AppHelper.getCheckContactList());
        if (selectCount == 1) {  // 单聊
            Contact contact = AppHelper.getCheckContactList().get(0);
            String employeeId = contact.getEmployeeId();
            String name = "".equals(StringUtils.value(contact.getName())) ? StringUtils.value(contact.getEmployeeName()) : StringUtils.value(contact.getName());

            Bundle bundle = new Bundle();
            bundle.putString("url", contact.getAvatar());
            RongIM.getInstance().startConversation(mContext, Conversation.ConversationType.PRIVATE,
                    employeeId, name, bundle);
            AppHelper.clearCheckList();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    EventBus.getDefault().post(new ChatListCloseEvent());
                    finish();
                }
            },1000);
        } else { // 创建群组
            String employeeIds = "";
            String groupName = "";
            String sourceFlag = "";
            for (int i = 0; i < selectCount; i++) {
                Contact contact = AppHelper.getCheckContactList().get(i);
                String employeeId = contact.getEmployeeId();
                employeeIds += (employeeId + ",");
                if (i < 5) {
                    groupName += ("".equals(StringUtils.value(contact.getName())) ? StringUtils.value(contact.getEmployeeName()) : StringUtils.value(contact.getName())) + "、";
                }
                sourceFlag += (TextUtils.isEmpty(contact.getSourceFlag()) ? ("1".equals(companyType) ? "0" : "1") : contact.getSourceFlag()) + ",";
            }

            ServiceRequestManager manager = ServiceRequestManager.getManager();
            HashMap<String, String> map = new HashMap<>();
            if ("1".equals(companyType)) {
                map.put("mainEmployeeId", ownerBean.getRows().getEmployeeId());
                employeeIds += ownerBean.getRows().getEmployeeId();
                sourceFlag += "0";
                groupName += ownerBean.getRows().getName();
            } else if ("2".equals(companyType)) {
                map.put("mainEmployeeId", serviceLoginBean.getRows().getEmployeeId());
                employeeIds += serviceLoginBean.getRows().getEmployeeId();
                sourceFlag += "1";
                groupName += serviceLoginBean.getRows().getName();
            }
            map.put("employeeId", employeeIds); // 群组人员用户集
            map.put("groupName", groupName); // 群组名称
            map.put("sourceFlag", sourceFlag); // 群组人员标示集
            manager.creatChatGroup(this, JsonMapUtil.mapToJson(map), TranspaintActivity.this);
        }
    }

    private void insteadGroup() {

        String empId = "";
        String sourceFlag = "";
        for (int i = 0; i < AppHelper.getCheckContactList().size(); i++) {
            Contact contact = AppHelper.getCheckContactList().get(i);
            empId += (contact.getEmployeeId() + ",");
            sourceFlag += (TextUtils.isEmpty(contact.getSourceFlag()) ? ("1".equals(companyType) ? "0" : "1") : contact.getSourceFlag()) + ",";
        }
        empId = empId.substring(0, empId.length() - 1);
        sourceFlag = sourceFlag.substring(0, sourceFlag.length() - 1);

        HashMap<String, String> map = new HashMap<>();
        map.put("employeeId", empId);
        map.put("groupId", groupId);
        map.put("sourceFlag", sourceFlag);
        map.put("groupName", RongUserInfoManager.getInstance().getGroupInfo(groupId).getName());

        ServiceRequestManager.getManager().creatChatGroup(this, JsonMapUtil.mapToJson(map), this);
    }


    public static void openActivity(Context context) {
        Intent intent = new Intent(context, TranspaintActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1://创建群组接口
                ChatAddBean bean = new Gson().fromJson(result, ChatAddBean.class);
                if (bean.getMessage().getCode() == 200) {
                    // 将群组信息 存入内存
                    RongUserInfoManager.getInstance().setGroupInfo(new Group(bean.getRows().getGroupId(), bean.getRows().getGroupName(), Uri.parse("xxx")));

                    RongIM.getInstance().startConversation(mContext, Conversation.ConversationType.GROUP,
                            bean.getRows().getGroupId(), bean.getRows().getGroupName());

                    // 发送通知消息
                    String name = "";
                    if ("1".equals(companyType)) {
                        name = ownerBean.getRows().getName();
                    } else if ("2".equals(companyType)) {
                        name = serviceLoginBean.getRows().getName();
                    }
                    if (TextUtils.isEmpty(groupId)) {
                        sendMsg(bean.getRows(), name + "创建了群组");
                    } else {
                        ArrayList<Contact> list = AppHelper.getCheckContactList();
                        String names = "";
                        for (Contact contact : list) {
                            names += ("".equals(StringUtils.value(contact.getName())) ? StringUtils.value(contact.getEmployeeName()) : StringUtils.value(contact.getName())) + "、";
                        }
                        names = names.substring(0, names.length() - 1);
                        sendMsg(bean.getRows(), name + "邀请" + names + "加入群组");
                    }
                    // 清除选中的列表
                    AppHelper.clearCheckList();
                    // 解决黑屏问题
                    EventBus.getDefault().post(new ChatCloseEvent());
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            EventBus.getDefault().post(new ChatListCloseEvent());
                            finish();
                        }
                    },1000);
                }
                break;
            default:
                break;
        }
    }

    private void sendMsg(ChatAddBean.RowsBean bean, String msg) {
        InformationNotificationMessage message = InformationNotificationMessage.obtain(msg);
        Message myMessage = Message.obtain(bean.getGroupId(), Conversation.ConversationType.GROUP, message);
        RongIM.getInstance().sendMessage(myMessage, null, null, new IRongCallback.ISendMediaMessageCallback() {
            @Override
            public void onProgress(Message message, int i) {

            }

            @Override
            public void onCanceled(Message message) {

            }

            @Override
            public void onAttached(Message message) {

            }

            @Override
            public void onSuccess(Message message) {

            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    @Override
    public void onException(int requestId, String code) {
        showCenterInfoMsg("创建群组失败");
        this.finish();
    }
}
